import logging
import json
import inspect
import functools
from typing import Dict, Any
from fastapi import APIRouter, HTTPException, Request
from fastapi.responses import JSONResponse
from app.services.shopify_translate_service import shopify_translate_service
from app.utils.error_handling import BadRequestError, InternalServerError

# 简单的模拟认证装饰器
def verify_token(f):
    @functools.wraps(f)
    async def wrapper(*args, **kwargs):
        # 这里可以实现简单的认证逻辑
        # 对于FastAPI，我们需要确保装饰器不会干扰参数解析
        return await f(*args, **kwargs) if inspect.iscoroutinefunction(f) else f(*args, **kwargs)
    return wrapper

# 简单的模拟限流装饰器
def rate_limit(limit=10, per=60):
    def decorator(f):
        @functools.wraps(f)
        async def wrapper(*args, **kwargs):
            # 这里可以实现简单的限流逻辑
            return await f(*args, **kwargs) if inspect.iscoroutinefunction(f) else f(*args, **kwargs)
        return wrapper
    return decorator

# 配置日志
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

# 创建FastAPI Router
router = APIRouter(prefix="/api/v1", tags=["Shopify Translation"])

@router.post('/translate-product-metafield')
@verify_token
@rate_limit(limit=10, per=60)  # 每分钟最多10次请求
async def translate_product_metafield(request: Request) -> Dict[str, Any]:
    """
    翻译产品文本并写入Shopify metafields的接口
    
    入参JSON格式：
    {
        "shopify_domain": "your-store.myshopify.com",  # Shopify店铺域名
        "product_id": 123456789,                       # 产品ID
        "namespace": "translate_namespace",           # Metafield命名空间（可选，默认translate_namespace）
        "key": "title",                              # Metafield键名
        "ori_text": "Original Product Title",        # 需要翻译的原始文本
        "target_language": "zh-CN",                  # 目标语言
        "type": "single_line_text_field"             # Metafield类型（可选，默认single_line_text_field）
    }
    
    返回格式：
    {
        "is_success": 1,  # 1表示成功，0表示失败
        "message": "Translation and metafield creation successful",
        "data": {
            "product_id": 123456789,
            "metafield_namespace": "translate_namespace",
            "metafield_key": "title_zh-CN",
            "translated_text": "翻译后的产品标题",
            "points_consumed": 50,
            "log_id": "translation_log_123456"
        }
    }
    """
    try:
        # 记录请求开始
        logger.info("接收到翻译并写入metafield的请求")
        
        # 检查请求内容类型
        content_type = request.headers.get('Content-Type', '')
        if not content_type.startswith('application/json'):
            logger.warning(f"请求内容类型不是JSON: {content_type}")
            raise HTTPException(
                status_code=400,
                detail={
                    "is_success": 0,
                    "error": "Content-Type must be application/json"
                }
            )
        
        # 解析请求体
        try:
            data = await request.json()
        except json.JSONDecodeError:
            logger.warning("请求体JSON格式无效")
            raise HTTPException(
                status_code=400,
                detail={
                    "is_success": 0,
                    "error": "Invalid JSON format in request body"
                }
            )
        
        if not data:
            logger.warning("请求体为空")
            raise HTTPException(
                status_code=400,
                detail={
                    "is_success": 0,
                    "error": "Request body cannot be empty"
                }
            )
        
        # 验证必需参数
        required_fields = ["shopify_domain", "product_id", "key", "ori_text", "target_language"]
        missing_fields = [field for field in required_fields if field not in data]
        
        if missing_fields:
            logger.warning(f"缺少必需参数: {missing_fields}")
            raise HTTPException(
                status_code=400,
                detail={
                    "is_success": 0,
                    "error": f"Missing required fields: {', '.join(missing_fields)}"
                }
            )
        
        # 提取参数
        shopify_domain = data.get("shopify_domain")
        product_id = data.get("product_id")
        namespace = data.get("namespace")  # 可选参数
        key = data.get("key")
        ori_text = data.get("ori_text")
        target_language = data.get("target_language")
        metafield_type = data.get("type")  # 可选参数
        
        # 验证参数类型
        if not isinstance(shopify_domain, str) or not shopify_domain.strip():
            raise HTTPException(
                status_code=400,
                detail={
                    "is_success": 0,
                    "error": "shopify_domain must be a non-empty string"
                }
            )
        
        # 确保product_id是整数
        try:
            product_id = int(product_id)
        except (ValueError, TypeError):
            raise HTTPException(
                status_code=400,
                detail={
                    "is_success": 0,
                    "error": "product_id must be an integer"
                }
            )
        
        if not isinstance(key, str) or not key.strip():
            raise HTTPException(
                status_code=400,
                detail={
                    "is_success": 0,
                    "error": "key must be a non-empty string"
                }
            )
        
        if not isinstance(ori_text, str):
            raise HTTPException(
                status_code=400,
                detail={
                    "is_success": 0,
                    "error": "ori_text must be a string"
                }
            )
        
        if not isinstance(target_language, str) or not target_language.strip():
            raise HTTPException(
                status_code=400,
                detail={
                    "is_success": 0,
                    "error": "target_language must be a non-empty string"
                }
            )
        
        # 记录参数信息（不记录完整的原始文本以保护隐私）
        logger.info(
            f"处理翻译请求: shopify_domain={shopify_domain}, "
            f"product_id={product_id}, key={key}, "
            f"text_length={len(ori_text)}, target_language={target_language}"
        )
        
        # 调用服务层处理翻译和写入
        result = shopify_translate_service.translate_and_write_metafield(
            shopify_domain=shopify_domain,
            product_id=product_id,
            namespace=namespace,
            key=key,
            ori_text=ori_text,
            target_language=target_language,
            type=metafield_type
        )
        
        # 根据结果返回响应
        if result.get("is_success") == 1:
            logger.info(f"翻译并写入metafield成功，产品ID: {product_id}")
            return result
        else:
            # 判断错误类型返回适当的状态码
            status_code = 400  # 默认为客户端错误
            error_info = result.get("error", "Unknown error")
            
            # 如果是积分不足或系统内部错误，返回500
            if isinstance(error_info, dict) and error_info.get("error") == "Insufficient points":
                status_code = 400  # 积分不足是客户端问题
            elif "server" in str(error_info).lower() or "internal" in str(error_info).lower():
                status_code = 500
            
            logger.error(f"翻译并写入metafield失败: {error_info}")
            raise HTTPException(
                status_code=status_code,
                detail=result
            )
            
    except BadRequestError as e:
        # 捕获业务逻辑错误
        logger.warning(f"业务逻辑错误: {str(e)}")
        raise HTTPException(
                status_code=400,
                detail={
                    "is_success": 0,
                    "error": str(e)
                }
            )
        
    except InternalServerError as e:
        # 捕获内部服务器错误
        logger.error(f"内部服务器错误: {str(e)}")
        raise HTTPException(
                status_code=500,
                detail={
                    "is_success": 0,
                    "error": str(e)
                }
            )
        
    except json.JSONDecodeError as e:
        # 捕获JSON解析错误
        logger.error(f"JSON解析错误: {str(e)}")
        raise HTTPException(
                status_code=400,
                detail={
                    "is_success": 0,
                    "error": "Invalid JSON format"
                }
            )
        
    except Exception as e:
        # 捕获其他未预期的错误
        logger.error(f"未预期的错误: {str(e)}", exc_info=True)
        return JSONResponse(
            status_code=500,
            content={
                "is_success": 0,
                "error": "Internal server error"
            }
        )

@router.get('/translate-product-metafield/health')
@rate_limit(limit=30, per=60)  # 健康检查接口限制更宽松
def health_check() -> Dict[str, Any]:
    """
    健康检查接口
    
    返回格式：
    {
        "status": "ok",
        "service": "shopify_translate_service",
        "timestamp": "2023-10-25T12:34:56Z"
    }
    """
    import datetime
    
    try:
        logger.info("健康检查请求")
        
        return {
                "status": "ok",
                "service": "shopify_translate_service",
                "timestamp": datetime.datetime.utcnow().isoformat() + "Z"
            }
        
    except Exception as e:
            logger.error(f"健康检查失败: {str(e)}")
            return JSONResponse(
                status_code=500,
                content={
                    "status": "error",
                    "error": str(e)
                }
            )